<?php

namespace app\admin\controller\user;

use app\admin\model\Admin;
use app\common\controller\Backend;
use app\common\model\Funds;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class User extends Backend
{



	protected $relationSearch = true;
	
    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('User');
        $list = [
        	'levelList' => \app\admin\model\User::$levelList,
	        'areaList' => \app\admin\model\User::$areaList
        ];
        $this->assignconfig($list);
        $this->assign($list);
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $with = ['recommend'];
            $total = $this->model
	            ->with($with)
                ->where($where)
                ->order($sort, $order)
                ->count();
            $list = $this->model
	            ->with($with)
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            foreach ($list as $k => $v) {
                $v->hidden(['password', 'salt']);
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
	    $row = $this->model->get($ids);
	    if (!$row) {
		    $this->error(__('No Results were found'));
	    }
	    $adminIds = $this->getDataLimitAdminIds();
	    if (is_array($adminIds)) {
		    if (!in_array($row[$this->dataLimitField], $adminIds)) {
			    $this->error(__('You have no permission'));
		    }
	    }
	    if ($this->request->isPost()) {
		    $params = $this->request->post("row/a");
		    if ($params) {
			    $params = $this->preExcludeFields($params);
			    
			    $diffMoney = $params['money'] - $row['money'];
			    if($diffMoney != 0 && !$params['remark']) {
			        $this->error('修改余额请添加说明');
			    }
			    $result = false;
			    Db::startTrans();
			    try {
			    	
			    	if($diffMoney != 0) {
			            $fundsModel = new Funds();
			            $fundsRes = $fundsModel->addRecord($row['id'], abs($diffMoney), $row['money'], $fundsModel::ACCOUNT_TYPE_BALANCE, $diffMoney > 0 ? $fundsModel::OPE_TYPE_PLUS : $fundsModel::OPE_TYPE_LESS, $fundsModel::TYPE_ADMIN_OPERATE, '', $params['remark']);
			            if(!$fundsRes) {
			            	throw new Exception('添加余额记录出错');
			            }
				    }
			    	
				    //是否采用模型验证
				    if ($this->modelValidate) {
					    $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
					    $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
					    $row->validateFailException(true)->validate($validate);
				    }
				    $result = $row->allowField(true)->save($params);
				    Db::commit();
			    } catch (ValidateException $e) {
				    Db::rollback();
				    $this->error($e->getMessage());
			    } catch (PDOException $e) {
				    Db::rollback();
				    $this->error($e->getMessage());
			    } catch (Exception $e) {
				    Db::rollback();
				    $this->error($e->getMessage());
			    }
			    if ($result !== false) {
				    $this->success();
			    } else {
				    $this->error(__('No rows were updated'));
			    }
		    }
		    $this->error(__('Parameter %s can not be empty', ''));
	    }
	    $this->view->assign("row", $row);
	    return $this->view->fetch();
    }

    /**
     * 设为战区管理员
     */
    public function headquarters() {
	    if ($this->request->isPost()) {
		    $params = $this->request->post("row/a");
		    if ($params) {
			
			    $user = $this->model->get($params['user_id']);
			    if ($user['level'] > 0) {
				    $levelList = \app\admin\model\User::$levelList;
				    $this->error('该用户已有' . $levelList[$user['level']] . '身份');
			    }
			
			    $res = $this->model->save(['level' => \app\admin\model\User::LEVEL_HEADQUARTERS], ['id' => $params['user_id']]);
			    if ($res) {
				    $this->success('设置成功');
			    } else {
				    $this->error('设置出错');
			    }
		    }
	    }
		return $this->view->fetch();
    }
	
	/**
	 * 删除
	 */
	public function del($ids = "")
	{
		!$ids && $this->error('请选择要删除的用户');
		if ($ids) {
			Db::startTrans();
			try {
				//检查代理信息
				
				
				//检查订单信息
				//检查佣金信息
				
				Db::commit();
			} catch (Exception $e) {
				Db::rollback();
				$this->error($e->getMessage());
			}
		}
	}
}
